<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Logic;


use App\Exceptions\ApiException;
use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms;
use Illuminate\Support\Facades\Redis;

class SmsLogic extends Logic
{

    private $accessKeyId = 'LTAIJ3BjxcM6d3Pm';

    private $accessKeySecret = 'FCeLpv64JTLogoIuwJSLiQy4FGENCy';

    private $response_code = [
        'isv.BUSINESS_LIMIT_CONTROL' => '发送短信频繁，请稍后再试',
        'isv.MOBILE_COUNT_OVER_LIMIT' => '手机号码数量超过限制',
        'isv.BLACK_KEY_CONTROL_LIMIT' => '手机号码黑名单管控',
        'isv.MOBILE_NUMBER_ILLEGAL' => '非法手机号'
    ];

    private $init_sign_name = '贵州英雄鸡';

    private function handle($phone, $code, $param, $sign_name = '贵州智星无限科技有限公司')
    {
        $client = new Client([
            'accessKeyId' => $this->accessKeyId,
            'accessKeySecret' => $this->accessKeySecret
        ]);
        $sms    = new SendSms();
        $sms->setPhoneNumbers($phone);
        $sms->setSignName($sign_name);
        $sms->setTemplateCode($code);
        $sms->setTemplateParam($param);
        $response = $client->execute($sms);
        if ($response->Code == 'OK') {
            foreach ((array)$phone as $value) {
                Redis::Hset('SMS_TIME', $value, time());
            }
        }
        return $response;
    }


    /**
     * 校验注册的短信验证码
     * @param $phone
     * @throws ApiException
     */
    public function checkRegisterSmsCode($phone,$code)
    {
        $storage_code = Redis::hGet('REGISTER_SMS_CODE', $phone);
        if (!empty($storage_code)) {
            $arr = explode('|', $storage_code);
            if (time() - $arr[1] > 600) {
                throw new ApiException('验证码已经过期,请重新获取');
            }
            if ($arr[0] != $code) {
                throw new ApiException('短信验证码有误');
            }
        } else {
            throw new ApiException('验证码失效');
        }
    }


    public function sendRedisError()
    {
        $last_send_time = Redis::Hget('SMS_TIME');
        //5分钟才发一次
        if (time() - $last_send_time > 300) {
            $this->handle(
                [15626104771, 18813987119],
                'SMS_130921434',
                ['serverid' => str_replace('.', '', $_SERVER['SERVER_ADDR']), 'level' => 3, 'reason' => 'redis随机数集合数据为空']
            );
        }
    }


    /**
     * 发送注册时的短信
     * @param $phone
     * @return
     * @throws ApiException
     */
    public function registerSms($phone)
    {
        $last_time = Redis::hGet('SMS_TIME', $phone);
        //两分钟发一次
        if (time() - $last_time < 120) {
            throw new ApiException('发送频繁,请稍后再发');
        }
        $code     = mt_rand(100000, 999999);
        $response = $this->handle($phone, 'SMS_133962279', ['code' => $code], $this->init_sign_name);
        if ($response->Code == 'OK') {
            Redis::hSet('REGISTER_SMS_CODE', $phone, $code . '|' . time());
            return $response->Code;
        } else {
            throw new ApiException($response->Message);
        }
    }

}